#! /bin/bash
export LANG=en_US.UTF-8

#WARNLIMIT=-1 		#警告值 超过该值则认为是需要告警
#ERRORLIMIT=-1 		#错误值 超过该值认为是错误

PORT=6379


FLAGE=
FLAGEID=
#是否输出FLAGPID
FLAGEOPID=1
#是否输出RUNTIME
RUNTIME=1
#是否输出STARTTIME
STARTTIME=0
VERBOSE=0

QUOTASTR=
quota=

function gotErr(){
	if [ "$1" -eq 0 ];then
		echo "mailstatedes=各项指标恢复正常 statedes=各项指标恢复正常|$DataResultStr"
	elif [ "$1" -eq 3 ];then 
		echo "mailstatedes=无法获取到指标,疑似组件故障,请确认并请检查监控脚本和运维平台配置 statedes=无法获取到指标,疑似组件故障,请确认并请检查监控脚本和运维平台配置 |$DataResultStr"
	fi

	exit $1
}

function parseFileds(){
	val1=$(echo "$CURNUM $2"| awk '{if($1<=$2){print 1}else{print 0}}')
	val2=$(echo "$CURNUM $3"| awk '{if($1<=$2){print 1}else{print 0}}')

	DataResultStr="$DataResultStr $1=$CURNUM;$2;$3;0;0"
}

#ps -eo pid,etime 是查询进程运行时间
function getRuntime(){
	CURNUM=$(ps -eo pid,etime | grep $FLAGEID |awk '{if($1=='$FLAGEID') print $2}')
}

#ps -eo pid,lstart是查询进程的开始时间
function getStarttime(){
	CURNUM=$(ps -eo pid,lstart | grep $FLAGEID |awk '{if($1=='$FLAGEID') print $2 ,$3 ,$4 ,$5 ,$6}')
}
#返回是否服务是否存活
function isAlive(){
  FLAGEID=$(netstat -lnp | grep $PORT | grep LISTEN | awk '{print $NF}'| awk -F '/' '{print $1}')
	isAliveStr=$(ps aux | grep zookeeper | grep server|grep "$FLAGEID" | grep -v grep | grep -v .sh| wc -l)
	if [[ "$isAliveStr" -lt 1 ]];then
#	    STARTZookeeper="$FLAGEID/bin/zkServer.sh start"
#	    echo "启动zookeeper"
#	    $STARTZookeeper
	    gotErr 3
	fi
	if [[  "$isAliveStr" -gt 1 ]];then
		gotErr 3
	fi

  if [ "$FLAGEOPID" -eq 1 ];then
		CURNUM=$FLAGEID
		parseFileds "FLAGEPID" $CURNUM $CURNUM
	fi
	if [ "$RUNTIME" -eq 1 ];then
			getRuntime
			parseTimeFileds "RUNTIME" $RUNTIME $RUNTIME		
	fi
	
	gotErr 0
}

function parseTimeFileds(){
	val1=$(echo "$CURNUM $2")
	val2=$(echo "$CURNUM $3")
  DataResultStr="$DataResultStr $1=$CURNUM;$2;$3;0;0"
}
#输出错误信息并且退出程序
function showHelp(){
	if [ "$1" != "" ];then
		echo "请输入$1"
	fi
	echo "check_zookeeper.sh 可以监听本地的zookeeper的状态 参数如下"
	echo "check_zookeeper.sh [-p <port>]"
	echo "-p <port> 特征字符串 表示监控哪个zookeeper端口"
	exit 1
}


while getopts "p:hv" arg
do
	case $arg in
		h)
			showHelp
			;;
		p)
			PORT=$OPTARG
			;;
		?) 
			showHelp
			;;
	esac
done

if [[ "$PORT" == "" ]];then
	showHelp "特征项"
fi

#插件正题部分 
#确定存活的

isAlive

